package com.cskaoyan.service;

import com.cskaoyan.mapper.AccountMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

/**
 * @author stone
 * @date 2022/03/31 20:48
 */
@Service
public class AccountServiceImpl implements AccountService{

    @Autowired
    AccountMapper accountMapper;

    @Autowired
    TransactionTemplate transactionTemplate;

    @Override
    public void transfer(Integer fromId, Integer destId, double money) {
        double fromMoney = accountMapper.selectMoneyById(fromId) - money;
        double destMoney = accountMapper.selectMoneyById(destId) + money;

        //匿名内部类 → 定义类、实例话对象
        transactionTemplate.execute(new TransactionCallback<Object>() {
            @Override
            public Object doInTransaction(TransactionStatus transactionStatus) {
                accountMapper.updateMoneyById(fromId, fromMoney);//提交事务
                int i = 1 / 0; //发生异常
                accountMapper.updateMoneyById(destId, destMoney);//执行不到了
                return null;
            }
        });



    }
}
